package com.qdaily.ui.ui.views;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.os.Build;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.qdaily.supportlibrary.util.LocalDisplay;
import com.qdaily.supportlibrary.util.QLog;
import com.qdaily.ui.R;
import com.qdaily.ui.data.DataBase.PraiseDAO;
import com.qdaily.ui.net.QDEnum;

/**
 * Created by song on 14/12/25.
 */
public class InputBar implements View.OnClickListener {

    private ResizeRelativeLayout resizeRelativeLayout;
    private FrameLayout blankView;
    private EditText editText;
    private Button sendBtn;

    private ImageView closeView;
    private TextView commentView;
    private TextView praiseView;
    private ImageView shareView;
    FrameLayout commentLayout;
    RelativeLayout shareLayout;

    private InputMethodManager imm;
    private Boolean isKeyBoardShow;

    private boolean isNeedPraise;

    private InputBarInterface barInterface;
    private InputBarKeyboardInterface barKeyboardInterface;

    private Activity mActivity;
    private LayoutInflater mLayoutInflater;

    private PraiseDAO praiseDAO;
    private int serverId;// 工具条绑定的这个Detail的服务器id
    private QDEnum.DetailEnum mDetailEnum; //工具条绑定的这个Detail的类型

    public InputBar(Activity mActivity, int inputBarViewId, Boolean isNeedPraise) {
        praiseDAO = PraiseDAO.getInstance();
        this.mActivity = mActivity;
        this.isNeedPraise = isNeedPraise;
        mLayoutInflater = LayoutInflater.from(mActivity);
        resizeRelativeLayout = (ResizeRelativeLayout) mActivity.findViewById(inputBarViewId);
        setUpView();
    }

    public InputBar(Activity mActivity, View view, int inputBarViewId, Boolean isNeedPraise) {
        praiseDAO = PraiseDAO.getInstance();
        this.mActivity = mActivity;
        this.isNeedPraise = isNeedPraise;
        mLayoutInflater = LayoutInflater.from(mActivity);
        resizeRelativeLayout = (ResizeRelativeLayout) view.findViewById(inputBarViewId);
        setUpView();
    }

    private InputBar() {
    }

    public View getInputBarView() {
        return resizeRelativeLayout;
    }

    public InputBarInterface getBarInterface() {
        return barInterface;
    }

    public void setBarInterface(InputBarInterface barInterface) {
        this.barInterface = barInterface;
    }

    public InputBarKeyboardInterface getBarKeyboardInterface() {
        return barKeyboardInterface;
    }

    public void setBarKeyboardInterface(InputBarKeyboardInterface barKeyboardInterface) {
        this.barKeyboardInterface = barKeyboardInterface;
    }

    public void setCommentCount(int count) {
        if (commentView != null)
        {
            if (count <= 0)
            {
                commentView.setText("  ");
            }
            else
            {
                commentView.setText("" + count);
            }
        }
    }

    private boolean isMinInputbar = false;
    private boolean isMinToolbar = false;
    public void configMinToolbar(){
        isMinToolbar = true;
        commentView.setVisibility(View.GONE);
        praiseView.setVisibility(View.GONE);
        shareView.setVisibility(View.GONE);
    }

    public void configMinInputbar(){
        isMinInputbar = true;
        shareLayout.setVisibility(View.GONE);
        commentLayout.setVisibility(View.VISIBLE);
    }

    public void setPraiseCount(int count) {
        if (praiseView != null)
        {
            if (count <= 0)
            {
                praiseView.setText("");
            }
            else
            {
                praiseView.setText("" + count);
            }

            String type = QDEnum.COPEnum.PAPER.value;
            if (mDetailEnum == QDEnum.DetailEnum.ARTICLE)
            {
                type = QDEnum.COPEnum.ARTICLE.value;
            }
            boolean isPraise = praiseDAO.isPraise(serverId, type);
            praiseView.setSelected(isPraise);
        }
    }

    public void setInputBarType(int serverId, QDEnum.DetailEnum mDetailEnum) {
        this.serverId = serverId;
        this.mDetailEnum = mDetailEnum;

        String type = QDEnum.COPEnum.PAPER.value;
        if (mDetailEnum == QDEnum.DetailEnum.ARTICLE)
        {
            type = QDEnum.COPEnum.ARTICLE.value;
        }
        boolean isPraise = praiseDAO.isPraise(serverId, type);
        praiseView.setSelected(isPraise);
    }

    public void clearText() {
        editText.setText("");
    }

    public void requestFocus(int parentCommentId) {
        shareLayout.setVisibility(View.GONE);
        commentLayout.setVisibility(View.VISIBLE);
        Integer id = (Integer) editText.getTag();
        if (id != null && id != parentCommentId)
        {
            clearText();
        }
        editText.setTag(parentCommentId);
        editText.requestFocus();
        imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, InputMethodManager.HIDE_IMPLICIT_ONLY);
    }

    private void setUpView() {
        blankView = (FrameLayout) resizeRelativeLayout.findViewById(R.id.inputbar_blank);
        editText = (EditText) resizeRelativeLayout.findViewById(R.id.inputbar_edittext);

        closeView = (ImageView) resizeRelativeLayout.findViewById(R.id.inputbar_closebtn);
        sendBtn = (Button) resizeRelativeLayout.findViewById(R.id.inputbar_sendbtn);
        shareView = (ImageView) resizeRelativeLayout.findViewById(R.id.inputbar_sharebtn);
        praiseView = (TextView) resizeRelativeLayout.findViewById(R.id.inputbar_praiseBtn);
        commentView = (TextView) resizeRelativeLayout.findViewById(R.id.inputbar_commentBtn);
        closeView.setOnClickListener(this);
        sendBtn.setOnClickListener(this);
        shareView.setOnClickListener(this);
        if (isNeedPraise)
            praiseView.setOnClickListener(this);
        else
            praiseView.setVisibility(View.GONE);
        commentView.setOnClickListener(this);

        commentLayout = (FrameLayout) resizeRelativeLayout.findViewById(R.id.toolbar_comment_layout);
        shareLayout = (RelativeLayout) resizeRelativeLayout.findViewById(R.id.toolbar_share_layout);

        resizeRelativeLayout.setOnResizeListener(new ResizeLinearLayout.OnResizeListener() {
            @Override
            public void OnResize(int w, int h, int oldw, int oldh) {
                QLog.w("ResizeLinearLayout", "h:" + h + ",oldh:" + oldh);
                if (!isMinToolbar)
                {
                    if (h < oldh) {
                        isKeyBoardShow = true;
                        blankView.setBackgroundResource(R.color.toolbar_blank_bg);
                        if (!isMinInputbar)
                        {
                            shareLayout.setVisibility(View.GONE);
                            commentLayout.setVisibility(View.VISIBLE);
                            editText.setText("");
                        }
                    } else if (h > oldh){
                        isKeyBoardShow = false;
                        if (Build.VERSION.SDK_INT < 16) {
                            blankView.setBackgroundDrawable(null);
                        } else {
                            blankView.setBackground(null);
                        }
                        if (!isMinInputbar)
                        {
                            shareLayout.setVisibility(View.VISIBLE);
                            commentLayout.setVisibility(View.GONE);
                            editText.setText("");
                        }
                    }

                }

                if (barKeyboardInterface != null) {
                    barKeyboardInterface.inputBarKeyboardChange(isKeyBoardShow);
                }
            }
        });

        blankView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (isKeyBoardShow) {
                    if (imm.isActive()) {
                        imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, InputMethodManager.HIDE_NOT_ALWAYS);
                    }
                    isKeyBoardShow = false;
                    return true;
                } else {
                    return false;
                }
            }
        });

        //评论相关
        imm = (InputMethodManager) mActivity.getSystemService(Context.INPUT_METHOD_SERVICE);
        editText.setImeOptions(EditorInfo.IME_ACTION_SEND);
        editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEND
                        || actionId == EditorInfo.IME_ACTION_DONE
                        || (event != null && KeyEvent.KEYCODE_ENTER == event.getKeyCode() && KeyEvent.ACTION_DOWN == event.getAction())) {
                    sendComment();
                }
                return false;
            }
        });

        if ( Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2)
        {
            resizeRelativeLayout.getViewTreeObserver().addOnWindowAttachListener(new ViewTreeObserver.OnWindowAttachListener() {
                @Override
                public void onWindowAttached() {

                }

                @Override
                public void onWindowDetached() {
                    if (mDetailEnum == null)
                        return;
                    if (praiseDAO != null && praiseView != null)
                    {
                        String praise_type = "";
                        switch (mDetailEnum) {
                            case ARTICLE:
                                praise_type = QDEnum.COPEnum.ARTICLE.value;
                                break;
                            case VOTE:
                                praise_type = QDEnum.COPEnum.PAPER.value;
                                break;
                            case VOTERESULT:
                                praise_type = QDEnum.COPEnum.PAPER.value;
                                break;
                            default:
                                praise_type = QDEnum.COPEnum.ARTICLE.value;
                                break;
                        }

                        int count = 0;
                        try {
                            count = Integer.valueOf(praiseView.getText().toString());
                        }
                        catch (Exception e)
                        {
                            count = 0;
                        }
                        praiseDAO.save(serverId, count==0? 2: (praiseView.isSelected() ? 1 : 2), praise_type);
                    }
                }
            });
        }
    }

    public enum EInputBarBtnType {
        share,
        comment,
        praise
    }

    private void sendComment()
    {
        if (barInterface != null) {
            Integer id = (Integer) editText.getTag();
            int parentCommentId = -1;
            if (id != null && id != 0)
            {
                parentCommentId = id;
            }
            barInterface.inputBarOnClickSendBtn(editText.getText().toString(), parentCommentId);
        }
        if (isKeyBoardShow) {
            if (imm.isActive()) {
                imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, InputMethodManager.HIDE_NOT_ALWAYS);
            }
            isKeyBoardShow = false;
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.inputbar_sendbtn:
                sendComment();
                break;
            case R.id.inputbar_closebtn:
                mActivity.finish();
                break;
            case R.id.inputbar_sharebtn:
                if (barInterface != null) {
                    barInterface.inputBarOnClickBtn(EInputBarBtnType.share);
                }
                break;
            case R.id.inputbar_commentBtn:
                if (barInterface != null) {
                    barInterface.inputBarOnClickBtn(EInputBarBtnType.comment);
                }
                break;
            case R.id.inputbar_praiseBtn:
                int count = 0;
                try {
                    count = Integer.valueOf(praiseView.getText().toString());
                }
                catch (Exception e)
                {
                    count = 0;
                }
                if (praiseView.isSelected())
                {
                    count--;
                }
                else
                {
                    count++;
                }
                if (count <= 0)
                {
                    praiseView.setText("");
                }
                else
                {
                    praiseView.setText("" + count);
                }
                praiseView.setSelected(!praiseView.isSelected());
                if (barInterface != null) {
                    barInterface.inputBarOnClickBtn(EInputBarBtnType.praise);
                }
                break;
        }
    }

    public interface InputBarKeyboardInterface {
        void inputBarKeyboardChange(boolean isShow);
    }

    public interface InputBarInterface {
        void inputBarOnClickBtn(EInputBarBtnType type);
        void inputBarOnClickSendBtn(String content, int parentCommentId); //-1则为文章评论，否则为子评论
    }
}